package org.opens.javaskill.dynamicProxy;

import lombok.Data;
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

public class DynamicProxyTestUseCglib {

    private CglibProxyHandle handle = new CglibProxyHandle();

    private QuestionService questionService = new QuestionService();

    /**
     * 功能:
     * <p></p>
     * 说明:
     * <pre>
     *     1.
     * </pre>
     */
    @Test
    public void test28() {
        handle.setProxyObject(questionService);
        QuestionService proxyQuestionService = handle.getProxy();

        proxyQuestionService.add();
    }

}

class QuestionService {

    public void add() {
        System.out.println("access to database add");
    }

}

@Data
class CglibProxyHandle implements InvocationHandler {

    private Object proxyObject;

    private MyTransactionManagerOne transactionManager = new MyTransactionManagerOne();

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        Object result = null;
        try {
            transactionManager.begin();
            result = method.invoke(proxyObject, objects);
            transactionManager.commit();
        } catch (Exception e) {
            e.printStackTrace();
            transactionManager.rollback();
        }
        return result;
    }

    public <T> T getProxy() {
        // 增强类
        Enhancer enhancer = new Enhancer();
        // 设置代理对象的class信息
        enhancer.setSuperclass(proxyObject.getClass());
        // 设置增强
        enhancer.setCallback(this);
        // 返回代理对象
        return (T) enhancer.create();
    }

}